package week_three.day02.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	private static final String className = "oracle.jdbc.OracleDriver";
	private static final String url = "jdbc:oracle:thin:@ZHA-ITA092-w7:1522:orcl";
	private static final String password = "123";
	private static final String username = "evan";
	private static BasicDataSource ds;
	// 线程安全的重量级对象 单例模式
	static {
		ds = new BasicDataSource();
		ds.setUrl(url);
		ds.setDriverClassName(className);
		ds.setUsername(username);
		ds.setPassword(password);
		ds.setMaxActive(5);
	}

	public static Connection createConnection() {
		Connection con = null;
		try {
			Class.forName(className);
			con = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public static Connection createConnectionWithDataSource() {
		Connection connection = null;
		try {
			connection = ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	public static void close(Connection con, PreparedStatement pst, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
